"""
DeepSeek API 客户端模块
用于与 DeepSeek 大模型 API 交互
"""

import os
import requests
from dotenv import load_dotenv
import logging
from typing import Dict, List, Union

# 设置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger("deepseek_client")

# 加载环境变量
load_dotenv()


class DeepSeekClient:
    """DeepSeek API 客户端类"""

    def __init__(self, api_key: str = None):
        """
        初始化 DeepSeek 客户端

        参数:
            api_key: DeepSeek API密钥，如果未提供则从环境变量获取
        """
        # 获取 API 密钥
        self.api_key = api_key or os.getenv("DEEPSEEK_API_KEY")
        if not self.api_key:
            logger.error("未找到DeepSeek API密钥! 请设置环境变量DEEPSEEK_API_KEY或传递api_key参数")
            raise ValueError("DeepSeek API密钥未配置")

        self.base_url = "https://api.deepseek.com/v1"
        self.headers = {
            "Authorization": f"Bearer {self.api_key}",
            "Content-Type": "application/json"
        }
        logger.info("DeepSeek客户端初始化完成")

    def chat_completion(
            self,
            model: str = "deepseek-chat",
            messages: List[Dict] = None,
            max_tokens: int = 500,
            temperature: float = 0.3,
            top_p: float = 1.0,
            stream: bool = False,
            **kwargs
    ) -> Dict:
        """
        调用聊天补全API

        参数:
            model: 使用的模型 (deepseek-r1, deepseek-coder等)
            messages: 消息列表
            max_tokens: 最大生成token数
            temperature: 温度参数 (0-2)
            top_p: 核采样参数
            stream: 是否流式响应

        返回:
            API响应字典
        """
        if messages is None:
            messages = []

        endpoint = f"{self.base_url}/chat/completions"
        payload = {
            "model": model,
            "messages": messages,
            "max_tokens": max_tokens,
            "temperature": temperature,
            "top_p": top_p,
            "stream": stream,
            **kwargs
        }

        logger.info(f"调用DeepSeek API: model={model}, messages={len(messages)}条")
        logger.debug(f"请求载荷: {payload}")

        try:
            response = requests.post(
                endpoint,
                headers=self.headers,
                json=payload,
                timeout=30  # 设置30秒超时
            )

            # 检查响应状态
            if response.status_code != 200:
                logger.error(f"API请求失败: 状态码={response.status_code}, 响应={response.text}")
                return {
                    "error": f"API请求失败: {response.status_code}",
                    "details": response.text
                }

            # 解析JSON响应
            data = response.json()
            logger.info(f"API调用成功! 消耗token数: {data['usage']['total_tokens']}")
            logger.debug(f"完整响应: {data}")
            return data

        except requests.exceptions.RequestException as e:
            logger.exception(f"API请求异常: {str(e)}")
            return {
                "error": f"请求异常: {str(e)}"
            }

    def list_models(self) -> List[str]:
        """获取可用模型列表"""
        endpoint = f"{self.base_url}/models"

        try:
            response = requests.get(endpoint, headers=self.headers, timeout=10)
            if response.status_code == 200:
                models = [model['id'] for model in response.json()['data']]
                logger.info(f"获取到 {len(models)} 个可用模型")
                return models
            else:
                logger.error(f"获取模型列表失败: {response.status_code}")
                return []
        except Exception as e:
            logger.exception(f"获取模型列表异常: {str(e)}")
            return []


# 创建全局客户端实例
try:
    deepseek_client = DeepSeekClient()
    logger.info("DeepSeek客户端实例创建成功")
except Exception as e:
    logger.error(f"创建DeepSeek客户端失败: {str(e)}")
    deepseek_client = None